import os
import git
import pandas as pd


TICKER_CANDIDATES_MEA = [
    ('Info', 'ExchangeRates', None),
    ('Spot', 'Binance', 'v1'),
    ('Spot', 'Bithumb', 'v2'),
    ('Spot', 'Gateio', 'v4'),
    ('Spot', 'Gdax', 'v1'),
    ('Spot', 'Huobi', 'v1'),
    ('Spot', 'Kraken', 'v1'),
    ('Spot', 'Mexc', 'v3'),
    ('Spot', 'Okex', 'v5'),
    ('Spot', 'Phemex', 'v1'),
    ('Spot', 'Upbit', 'v1'),
]


_KLINE_SYMBOL_PATHES = [
    '../coin_deploy/support_info/kline_config/kline_symbols_list.csv',
    'python/coin_deploy/support_info/kline_config/kline_symbols_list.csv'
]


def get_kline_symbol_path(kline_symbol_path):
  kline_symbol_path = kline_symbol_path or _KLINE_SYMBOL_PATHES
  git_root = git.Repo(os.getcwd(), search_parent_directories=True).git.rev_parse(
      "--show-toplevel")
  kline_path = [
      os.path.join(git_root, p)
      for p in kline_symbol_path
      if os.path.exists(os.path.join(git_root, p))
  ][0]
  kline_path = os.path.abspath(kline_path)
  return kline_path


def _gen_exchange_rate_coins(kline_symbol_path):
  kline_symbol_path = get_kline_symbol_path(kline_symbol_path)
  assert os.path.isfile(kline_symbol_path), kline_symbol_path
  symbol_df = pd.read_csv(kline_symbol_path)
  symbol_df = symbol_df[symbol_df['market_type'] == 'Spot']
  symbol_df['base'] = symbol_df['symbol'].apply(lambda x: x.split('-')[0])
  symbol_df['quote'] = symbol_df['symbol'].apply(lambda x: x.split('-')[-1])
  exchange_rate_coins = {}
  exchange_candidates = list(symbol_df['exchange'].unique())
  for exchange in exchange_candidates:
    exchange_coins = symbol_df['base'][symbol_df['exchange'] == exchange].tolist() \
                     + symbol_df['quote'][symbol_df['exchange'] == exchange].tolist()
    exchange_coins = list(set(exchange_coins))
    exchange_coins.sort()
    exchange_rate_coins[exchange] = exchange_coins
  return exchange_rate_coins


EXCHANGE_RATE_COINS = _gen_exchange_rate_coins(None)
COIN_LIST = []
for _, coins in EXCHANGE_RATE_COINS.items():
  COIN_LIST += coins
COIN_LIST = sorted(list(set(COIN_LIST)))
